package com.cskaoyan.day01.linkdemo;

/**
 * 链表反转
 * @author stone
 * @date 2022/01/27 14:37
 */
public class LinkedDemo5 {

    public static void main(String[] args) {
        Node node1 = new Node("红");
        Node node2 = new Node("橙");
        Node node3 = new Node("黄");
        Node node4 = new Node("绿");
        Node node5 = new Node("青");
        Node node6 = new Node("蓝");
        Node node7 = new Node("紫");

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        Node reverse = reverse(node1);
        LinkedDemo1.show(reverse);
    }

    private static Node reverse(Node head) {
        if (head == null) {
            throw new RuntimeException("链表为空");
        }
        Node current = head;
        Node reverse = null;
        Node next;
        //当前结点只要不是null就遍历
        while (current != null) {
            //先布局next结点
            next = current.next;
            //当前结点插入到reverse前面
            current.next = reverse;
            //将current定义reverse
            reverse = current;
            //current在原先链表的后移
            //current = current.next  //这个是错误的写法，这个是在reverse中遍历，而我们应该在原先的链表中遍历
            current = next;
        }
        return reverse;
    }
}
